package com.user.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.user.entity.User;
import com.user.service.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		try {
			//判断表单中是否有multipart属性
			boolean isMultipart=ServletFileUpload.isMultipartContent(request);
			if(isMultipart){
				//创建工厂类
				FileItemFactory factory=new DiskFileItemFactory();
				//创建解析器
				ServletFileUpload upload=new ServletFileUpload(factory);
				//设置单个文件大小
				//upload.setSizeMax(20480);
				User user=new User();
				//通过parseRequest解析form表单中所有请求字段，并保存到item集合中
				List<FileItem> items=upload.parseRequest(request);
				//遍历items数据
				for (FileItem item : items) {
					//如果是普通的form元素
					if(item.isFormField()) {
						String filename=item.getFieldName();
						String value=item.getString("utf-8");
						//System.out.println("普通form元素"+filename+":"+value);
						if(filename.equals("username")) {
							user.setUsername(value);
						}else if(filename.equals("password")) {
							user.setPassword(value);
						}else if(filename.equals("email")) {
							user.setEmail(value);
						}else if(filename.equals("address")) {
							user.setAddress(value);
						}else if(filename.equals("hobby")) {
							user.setHobby(value);
						}
					}else {
						String filename=item.getName();
						System.out.println("文件"+filename);
						//获取文件名的后缀
						String suffix=filename.substring(filename.lastIndexOf('.'));
						//为了防止上传到服务器中的文件重名，所以在上传的时候我们可以将文件进行自动生成前缀，只保留后缀，再拼接到一块的方法，来避免文件重名
						UUID uuid=UUID.randomUUID();
						String prefix=uuid.toString();
						//拼接后的文件名
						String savefilename=prefix+suffix;
						savefilename=savefilename.replace("-", "");
						//System.out.println("要保存的文件名为"+savefilename);
						String path=request.getSession().getServletContext().getRealPath("images");
						user.setPhoto(savefilename);
						System.out.println("图片路径是："+path);
						InputStream is=item.getInputStream();
						OutputStream os=new FileOutputStream(new File(path+File.separator+savefilename));
						byte[] b=new byte[1024];
						int len;
						while((len=is.read(b))!=-1) {
							os.write(b, 0, len);
						}
						is.close();
						os.close();
					}

				}
				System.out.println("用户地址是："+user.getAddress());
				UserService userservice=new UserService();
				boolean result=userservice.addUser(user);
				if(result) {
					//request.getRequestDispatcher("LoginPreServlet").forward(request, response);
					response.sendRedirect("userlist");
				}else {
					response.sendRedirect("error.jsp");
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
